package com.example.bookkeepingelf.business.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Editable;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

import com.alibaba.fastjson.JSONObject;
import com.example.bookkeepingelf.R;
import com.example.bookkeepingelf.base.utils.AsyncUtils;
import com.example.bookkeepingelf.base.utils.ResourceUtils;
import com.example.bookkeepingelf.base.utils.StringUtils;
import com.example.bookkeepingelf.base.utils.ToastUtils;
import com.example.bookkeepingelf.business.adapter.SelectIconRecyclerViewAdapter;
import com.example.bookkeepingelf.business.constant.AccountBookConstant;
import com.example.bookkeepingelf.business.database.AppDatabase;
import com.example.bookkeepingelf.business.database.dao.AccountBookDao;

import com.example.bookkeepingelf.business.database.entity.AccountBook;

import java.util.Date;
import java.util.List;
import java.util.Objects;

import cn.hutool.core.collection.CollectionUtil;


/**
 * 新增账本活动
 */
public class AddAccountBookActivity extends AppCompatActivity {

    private ImageView cancelImageView;

    private ImageView oKImageView;

    private ImageView iconImageView;

    private EditText accountBookNameEditText;

    private List<String> icons;

    private boolean updateFlag = false;

    private AccountBook updateAccountBook;

    private Handler handler = new Handler(Looper.myLooper()){

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    Pair<Boolean, String> obj = (Pair<Boolean, String>)msg.obj;

                    if (obj.first) {
                        finish();
                    }else {
                        ToastUtils.showCustomToast(AddAccountBookActivity.this, AddAccountBookActivity.this.oKImageView, obj.second);
                    }
                    break;
                case 2:
                    ToastUtils.showCustomToast(AddAccountBookActivity.this, AddAccountBookActivity.this.oKImageView, "创建失败");
                    break;
            }
        }
    };

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_account_book);
        // 初始化视图
        this.cancelImageView = findViewById(R.id.image_cancel);
        this.oKImageView = findViewById(R.id.image_ok);
        this.iconImageView = findViewById(R.id.icon);
        this.accountBookNameEditText = findViewById(R.id.account_book_name_edit_text);
        // 判断是否是更新账本
        this.isUpdate();
        // 初始化图标数据
        this.initIconDate();
        // 取消设置
        this.cancelSetting();
        // 确定设置
        this.oKSetting();
        // 设置图标选择器
        this.selectIconSetting();

    }

    private void isUpdate() {
        Intent intent = getIntent();
        if (intent != null) {
            this.updateFlag = intent.getBooleanExtra(AccountBookConstant.IS_UPDATE, false);
            if (this.updateFlag) {
                String stringExtra = intent.getStringExtra(AccountBookConstant.UPDATE_ACCOUNT_BOOK);
                if (StringUtils.isNotBlank(stringExtra)) {
                    //更新
                    JSONObject jsonObject = JSONObject.parseObject(stringExtra);
                    this.updateAccountBook = JSONObject.toJavaObject(jsonObject, AccountBook.class);
                    this.accountBookNameEditText.setText(updateAccountBook.getAccountBookName());
                    this.iconImageView.setImageResource(ResourceUtils.getIconResourceId(this, updateAccountBook.getIcon()));
                }
            }

        }

    }

    private void selectIconSetting() {
        // 获取 LayoutInflater 实例
        LayoutInflater inflater = LayoutInflater.from(this);
        // 从 XML 文件中加载视图
        View fragmentIconSelectionView = inflater.inflate(R.layout.fragment_icon_selection, null);
        // 设置 RecyclerView
        RecyclerView recyclerView = fragmentIconSelectionView.findViewById(R.id.recycler_view_icons);
        // 假设有一个名为 iconNames 的字符串数组包含了所有的图标名称
        SelectIconRecyclerViewAdapter iconAdapter = new SelectIconRecyclerViewAdapter(this, icons, iconImageView); // 传递实际的数据源
        recyclerView.setAdapter(iconAdapter);
        // 设置网格布局管理器
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 6);
        recyclerView.setLayoutManager(gridLayoutManager);

        //2、设置 PopupWindow
        // 设置 PopupWindow
        int width = LinearLayout.LayoutParams.MATCH_PARENT;
        int height = LinearLayout.LayoutParams.WRAP_CONTENT;
        final PopupWindow popupWindow = new PopupWindow(fragmentIconSelectionView, width, height, true);
        popupWindow.setOutsideTouchable(true); // 点击外部区域可消失
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); // 设置背景透明
        if (icons.size() >= 24) {
            popupWindow.setHeight(1000);
        }
        // 显示 PopupWindow
        LinearLayout linearLayout = findViewById(R.id.btn_select_icon_daily_ledger);
        linearLayout.setOnClickListener(v -> {
            popupWindow.showAsDropDown(v);
        });
    }

    private void oKSetting() {
        this.oKImageView.setOnClickListener(v -> {
            if (this.updateFlag) {
                this.update();
            }else {
                this.create();
            }

        });
    }

    private void update() {
        AccountBook accountBook = this.buildAccountBook(this.updateAccountBook);
        this.createOrUpdateAccountBook(accountBook);
    }

    private void create() {
        AccountBook accountBook = this.buildAccountBook(new AccountBook());
        this.createOrUpdateAccountBook(accountBook);
    }

    private AccountBook buildAccountBook(AccountBook accountBook) {
        Editable accountBookName = accountBookNameEditText.getText();
        Drawable drawable = iconImageView.getDrawable();
        String iconName = ResourceUtils.getResourceNameByDrawable(this, drawable);
        //获取账本名称和账本图标
        accountBook.setAccountBookName(accountBookName.toString());
        accountBook.setIcon(iconName);
        if (Objects.isNull(accountBook.getAmount())){
            accountBook.setAmount(AccountBookConstant.ZERO);
        }
        if (Objects.isNull(accountBook.getCreateTime())) {
            accountBook.setCreateTime(new Date());
        }
        accountBook.setUpdateTime(new Date());
        accountBook.setMain(false);
        return accountBook;
    }

    private void createOrUpdateAccountBook(AccountBook accountBook) {
        if (StringUtils.isBlank(accountBook.getAccountBookName())) {
            ToastUtils.showCustomToast(this, oKImageView, "账本名称不能为空");
        }
        // 去除前后空格
        String accountBookName = StringUtils.trim(accountBook.getAccountBookName());
        accountBook.setAccountBookName(accountBookName);

        Drawable drawable = iconImageView.getDrawable();
        if (Objects.isNull(drawable)) {
            ToastUtils.showCustomToast(this, oKImageView, "请选择图标");
        }

        boolean modifyFlag = accountBook.getId() != null;

        //保存
        // 初始化数据库
        AppDatabase database = AppDatabase.getDatabase(this);
        AccountBookDao accountBookDao = database.accountBookDao();
        AsyncUtils.runSingle(() -> {
            Pair<Boolean, String> result = new Pair<>(true, "OK");

            AccountBook existAccountBook = accountBookDao.getAccountBookByName(accountBook.getAccountBookName());
            if (Objects.nonNull(existAccountBook)) {
                if (modifyFlag) {
                    if (!existAccountBook.getId().equals(accountBook.getId())) {
                        result = new Pair<>(false, "账本名称重复");
                    }
                }else {
                    result = new Pair<>(false, "账本名称重复");
                }
            }

            if (result.first) {
                if (modifyFlag) {
                    accountBook.setUpdateTime(new Date());
                    accountBookDao.update(accountBook);
                }else {
                    accountBookDao.insert(accountBook);
                }
            }
            Message message = new Message();
            message.what = 1;
            message.obj = result;
            handler.sendMessage(message);
        }, true);

    }

    /**
     * 取消设置
     */
    private void cancelSetting() {
        this.cancelImageView.setOnClickListener(v -> finish());
    }

    private void initIconDate() {
        List<String> zTb = ResourceUtils.getDrawableNamesStartingWith( "z_tb_");
        if (CollectionUtil.isEmpty(zTb)) {
            return;
        }

        icons = zTb;

    }
}